//
//  MLDropdownView.m
//  MSHandbook
//
//  Created by molon on 14/11/12.
//  Copyright (c) 2014年 molon. All rights reserved.
//

#import "MLDropdownView.h"

#define kPadding 10.0f

#define kAnimateDuration .20f

@interface MLDropdownView()

@property (nonatomic, strong) UIView *containerView;

@property (nonatomic, strong) UILabel *messageLabel;

@property (nonatomic, assign) NSTimeInterval lastShowTime;
@property (nonatomic, assign) BOOL isInHideAnimation;
@property (nonatomic, assign) BOOL isInShowAnimation;

@end

@implementation MLDropdownView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        self.backgroundColor = [UIColor clearColor];
        self.clipsToBounds = YES;
        self.userInteractionEnabled = YES;
        [self addSubview:self.containerView];
    }
    return self;
}

- (void)dealloc
{
	DLOG(@"dealloc %@",NSStringFromClass([self class]));
}


- (void)willMoveToSuperview:(UIView *)newSuperview
{
    [super willMoveToSuperview:newSuperview];
    
    if ([self.superview isKindOfClass:[UIScrollView class]]) {
        //删除KVO
        [self.superview removeObserver:self forKeyPath:@"contentOffset" context:nil];
    }
}

- (void)didMoveToSuperview
{
    [super didMoveToSuperview];
    
    if ([self.superview isKindOfClass:[UIScrollView class]]) {
        //TODO:其实还应该处理下当前的custom offset(自定义)，不一定在此处理
        //添加KVO
        [self.superview addObserver:self forKeyPath:@"contentOffset" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionInitial context:nil];
    }
}

#pragma mark - kvo
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if ([@"contentOffset" isEqualToString:keyPath]) {
        UIScrollView *scrollView = (UIScrollView*)self.superview;
        CGRect frame = self.frame;
        frame.origin.y = scrollView.contentOffset.y+scrollView.contentInset.top;
        frame.origin.x = scrollView.contentOffset.x+scrollView.contentInset.left;
        self.frame = frame;
    }else{
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}


#pragma mark - getter
- (UILabel *)messageLabel
{
    if (!_messageLabel) {
        UILabel* label = [[UILabel alloc]init];
        label.backgroundColor = [UIColor clearColor];
        label.textColor = kDefaultMessageColor;
        label.font = kDefaultMessageFont;
        label.numberOfLines = 0;
        
        _messageLabel = label;
    }
    return _messageLabel;
}

- (UIView *)containerView
{
	if (!_containerView) {
		_containerView = [UIView new];
        _containerView.backgroundColor = kDefaultBackgroundColor;
        [_containerView addSubview:self.messageLabel];
	}
	return _containerView;
}

#pragma mark - layout
- (void)layoutSubviews
{
	[super layoutSubviews];
    
    CGFloat baseWidth = self.superview.frame.size.width;
    
    CGSize size = [self preferredMessageLabelSizeWithWidth:baseWidth-kPadding*2];
    self.messageLabel.frame = CGRectMake((baseWidth-size.width)/2, kPadding, size.width, size.height);
    
    CGRect frame = self.frame;
    //修正高度
    frame.size.height = size.height+kPadding*2;
    frame.size.width = baseWidth;
    self.frame = frame;
    
    CGRect containerFrame = self.containerView.frame;
    containerFrame.size = self.bounds.size;
    self.containerView.frame = containerFrame;
}

- (CGSize)preferredMessageLabelSizeWithWidth:(CGFloat)width
{
    CGSize size = CGSizeZero;
    NSDictionary *attribute = @{NSFontAttributeName: self.messageLabel.font};
    size = [self.messageLabel.text boundingRectWithSize:CGSizeMake(width, MAXFLOAT)
                                                options:NSStringDrawingUsesLineFragmentOrigin attributes:attribute context:nil].size;
    return size;
}

#pragma mark - touch
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    [super touchesEnded:touches withEvent:event];
    
    if (self.didTapBlock) {
        self.didTapBlock();
    }
    
    if (self.superview) {
        [[self class]hideInView:self.superview animated:YES];
    }
}

#pragma mark - call
+ (CGFloat)preferredOffsetYForView:(UIView*)view
{
    CGFloat customOffsetY = 0.0f;
    if ([view isKindOfClass:[UIWindow class]]) {
        CGRect appFrame = [[UIScreen mainScreen] applicationFrame];
        customOffsetY = appFrame.origin.y;
    }else{
        id nextResponder = [view nextResponder];
        if ([nextResponder isKindOfClass:[UIViewController class]]) {
            //检测其是否和状态栏重叠
            CGPoint inWindowOrgin = [view convertPoint:CGPointZero toView:nil];
            CGRect statusBarFrame = [[UIApplication sharedApplication]statusBarFrame];
            if (CGRectContainsPoint(statusBarFrame, inWindowOrgin)) {
                customOffsetY = [[UIApplication sharedApplication]statusBarFrame].size.height-inWindowOrgin.y;
            }
            
            UIViewController *vc = nextResponder;
            if (vc.navigationController.navigationBar&&!vc
                .navigationController.navigationBarHidden) {
                customOffsetY += vc.navigationController.navigationBar.intrinsicContentSize.height;
            }
        }
    }
    return customOffsetY;
}

+ (MLDropdownView*)dropdownViewInView:(UIView*)view
{
    for (UIView *subView in [view subviews]) {
        if ([subView isKindOfClass:[MLDropdownView class]]) {
            return (MLDropdownView*)subView;
        }
    }
    return nil;
}

+ (MLDropdownView*)showInView:(UIView*)view message:(NSString*)message animated:(BOOL)animated
{
    return [[self class]showInView:view message:message backgroundColor:nil messageColor:nil font:nil animated:animated];
}

+ (MLDropdownView*)showInView:(UIView*)view message:(NSString*)message backgroundColor:(UIColor *)backgroundColor messageColor:(UIColor*)messageColor font:(UIFont*)font animated:(BOOL)animated
{
    return [[self class]showInView:view message:message backgroundColor:backgroundColor messageColor:messageColor font:font customOffsetY:[[self class]preferredOffsetYForView:view] animated:animated];
}

+ (MLDropdownView*)showInView:(UIView*)view message:(NSString*)message backgroundColor:(UIColor *)backgroundColor messageColor:(UIColor*)messageColor font:(UIFont*)font customOffsetY:(CGFloat)customOffsetY animated:(BOOL)animated
{
    if (!view) {
        return nil;
    }
    
    //找到当前这个view已经有的dropdownView
    MLDropdownView *dropdownView = [[self class] dropdownViewInView:view];
    
    if (!dropdownView) {
        dropdownView = [MLDropdownView new];
        [view addSubview:dropdownView];
    }
    
    //设置一些自定义参数
    dropdownView.containerView.backgroundColor = backgroundColor?:kDefaultBackgroundColor;
    dropdownView.messageLabel.textColor = messageColor?:kDefaultMessageColor;
    dropdownView.messageLabel.font = font?:kDefaultMessageFont;
    
    //恢复下
    dropdownView.containerView.transform = CGAffineTransformIdentity;
    
    dropdownView.messageLabel.text = message;
    [dropdownView setNeedsLayout];
    [dropdownView layoutIfNeeded];
    
    //customOffsetY暂时不支持scrollView
    if (![view isKindOfClass:[UIScrollView class]]) {
        CGRect frame = dropdownView.frame;
        frame.origin.y = customOffsetY;
        dropdownView.frame = frame;
    }
    
    //动画
    if (animated&&!dropdownView.isInShowAnimation) {
        dropdownView.isInShowAnimation = YES;
        
        dropdownView.containerView.transform = CGAffineTransformMakeTranslation(0, -dropdownView.containerView.frame.size.height);
        [UIView animateWithDuration:kAnimateDuration delay:0.0f options:UIViewAnimationOptionBeginFromCurrentState|UIViewAnimationOptionCurveEaseOut animations:^{
            dropdownView.containerView.transform = CGAffineTransformIdentity;
        } completion:^(BOOL finished) {
            dropdownView.isInShowAnimation = NO;
        }];
    }else{
        dropdownView.isInShowAnimation = NO;
    }
    
    dropdownView.lastShowTime = [[NSDate date]timeIntervalSince1970];
    
    return dropdownView;
}

+ (MLDropdownView*)showInView:(UIView*)view message:(NSString*)message animated:(BOOL)animated hideAfterDelay:(NSTimeInterval)delay
{
    return [self showInView:view message:message backgroundColor:nil messageColor:nil font:nil animated:animated hideAfterDelay:delay];
}

+ (MLDropdownView*)showInView:(UIView*)view message:(NSString*)message backgroundColor:(UIColor *)backgroundColor messageColor:(UIColor*)messageColor font:(UIFont*)font animated:(BOOL)animated hideAfterDelay:(NSTimeInterval)delay
{
    return [self showInView:view message:message backgroundColor:backgroundColor messageColor:messageColor font:font customOffsetY:[[self class]preferredOffsetYForView:view] animated:animated hideAfterDelay:delay];
}

+ (MLDropdownView*)showInView:(UIView*)view message:(NSString*)message backgroundColor:(UIColor *)backgroundColor messageColor:(UIColor*)messageColor font:(UIFont*)font customOffsetY:(CGFloat)customOffsetY animated:(BOOL)animated hideAfterDelay:(NSTimeInterval)delay
{
    if (animated) {
        delay += kAnimateDuration;
    }
    
    MLDropdownView *dropdownView = [[self class]showInView:view message:message backgroundColor:backgroundColor messageColor:messageColor font:font customOffsetY:customOffsetY animated:animated];
    
    if (!dropdownView) {
        return dropdownView;
    }
    
    
    NSTimeInterval lastShowTime = dropdownView.lastShowTime;
    //等待delay后隐藏
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delay * NSEC_PER_SEC));
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
        if (!dropdownView.superview||![dropdownView.superview isEqual:view]) {
            return;
        }
        //这里如果在显示过程中，重新调用了show的话能重置时间，保证这里的hide只对这一个show有效
        if (dropdownView.lastShowTime == lastShowTime) {
            [[self class]hideInView:view animated:animated];
        }
    });
    
    return dropdownView;
}

+ (BOOL)hideInView:(UIView*)view animated:(BOOL)animated
{
    //找到当前这个view已经有的dropdownView
    MLDropdownView *dropdownView = [[self class] dropdownViewInView:view];
    
    if (!dropdownView) {
        return NO;
    }else{
        if (animated) {
            if (dropdownView.isInHideAnimation) {
                return YES;
            }
            
            dropdownView.isInHideAnimation = YES;
            NSTimeInterval lastShowTime = dropdownView.lastShowTime;
            
            dropdownView.containerView.transform = CGAffineTransformIdentity;
            [UIView animateWithDuration:kAnimateDuration delay:0.0f options:UIViewAnimationOptionBeginFromCurrentState|UIViewAnimationOptionCurveEaseOut animations:^{
                dropdownView.containerView.transform = CGAffineTransformMakeTranslation(0, -dropdownView.containerView.frame.size.height);
            } completion:^(BOOL finished) {
                dropdownView.isInHideAnimation = NO;
                if (dropdownView.lastShowTime == lastShowTime) {
                    dropdownView.containerView.transform = CGAffineTransformIdentity;
                    [dropdownView removeFromSuperview];
                }
            }];
        }else{
            dropdownView.isInHideAnimation = NO;
            [dropdownView removeFromSuperview];
        }
        return YES;
    }
}

@end
